#include "student_view.h"
#include "ui_student_view.h"
#include "widget_conversation.h"
#include "ui_widget_conversation.h"
#include <QGraphicsLineItem>
#include <cmath>
#include <iostream>
#include <QBrush>
#include <Qt>
#include "widget_header_buttons.h"

student_view::student_view(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::student_view)
{
    setMainWindowTitle("Student Information");
    ui->setupUi(this);

    ui->gridLayout->addWidget(new widget_header_buttons(this),0,0,0,0);
    ui->tableWidget->resizeColumnsToContents();
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(ui->tableWidget, SIGNAL(cellChanged(int,int)), ui->tableWidget, SLOT(resizeColumnsToContents()));

    scene = new QGraphicsScene();
    ui->graphicsView->setScene(scene);

    update_graphicsView();

    connect(ui->addNoteButton, SIGNAL(clicked()), this, SLOT(note_added()));

    widget_conversation* convo = new widget_conversation(this, "<conversation with John Smith>", "Send John Smith a message");
    ui->verticalLayout->addWidget(convo);
}

student_view::~student_view()
{
    delete ui;
}
/*
void student_view::on_studentListView_clicked()
{
    emit (changeScene(STUDENT_LIST_VIEW));
}
*/
static float fn(float x)
{
    return 5 * sin(x);
}

void student_view::note_added()
{
    QString msg = ui->noteLineEdit->text();
    if (msg.length() != 0)
    {
        add_note(msg);
        ui->noteLineEdit->clear();
    }
}

void student_view::add_note(QString note)
{
    static float currNote = 0.0f;

    notes.push_back(std::pair<QString,float>(note, currNote));

    currNote += 10.0f;

    update_graphicsView();
}

void student_view::update_graphicsView()
{
    scene->clear();

    float width = ui->graphicsView->size().width() - 5;
    float height = ui->graphicsView->size().height() - 5;

    int step = 50;

    QPen p;
    QBrush b;
    b.setColor(QColor(255,0,0));
    b.setStyle(Qt::SolidPattern);
    p.setColor(QColor(255,0,0));
    p.setWidth(2);
    for (unsigned i = 0; i < notes.size(); i++)
    {
        scene->addRect(notes[i].second, 0, 5.0f, height,p,b)
                ->setToolTip(notes[i].first);
    }

    for (int i = 0; i < step; i++)
    {
        float currX = i * (width/step);
        float nextX = (i+1) * (width/step);

        float currY = height/2 + fn(currX);
        float nextY = height/2 + fn(nextX);

        scene->addLine(currX,currY,nextX,nextY);
    }
}

void student_view::on_testInfoButton_clicked()
{
    emit changeScene(TEST_INFO_VIEW);
}

void student_view::on_noteLineEdit_returnPressed()
{
    note_added();
}
